package main

import (
	"io/ioutil"
	"log"
	"os"
)

type str string

func (s str) empty() bool {
	return s == ""
}

type filePath str

func (file filePath) empty() bool {
	return file == ""
}
func (file filePath) exists() bool {
	_, err := os.Stat(string(file))
	if err == nil {
		return true
	}
	return false
}

type Config struct {
	RegionId       str
	AccessKeyId    str
	AccessSecret   str
	DomainName     str
	SSLProtocol    str
	CertName       str
	CertType       str
	SSLPubFilePath filePath
	SSLPriFilePath filePath
	ForceSet       str

	sSLPub str
	sSLPri str
	//configPath str
}

type ConfigList struct {
	RegionId     str
	AccessKeyId  str
	AccessSecret str
	SSLProtocol  str
	CertType     str
	ForceSet     str

	List []Config
}

func formatConfig(configList ConfigList) ConfigList {
	if configList.RegionId.empty() {
		configList.RegionId = "cn-hangzhou"
	}
	if configList.SSLProtocol.empty() {
		configList.SSLProtocol = "on"
	}
	if configList.CertType.empty() {
		configList.CertType = "upload"
	}
	if configList.ForceSet.empty() {
		configList.ForceSet = "1"
	}

	for i := 0; i < len(configList.List); i++ {
		config := &configList.List[i]

		if config.AccessKeyId.empty() {
			config.AccessKeyId = configList.AccessKeyId
		}
		if config.AccessSecret.empty() {
			config.AccessSecret = configList.AccessSecret
		}

		if config.RegionId.empty() {
			config.RegionId = configList.RegionId
		}
		if config.SSLProtocol.empty() {
			config.SSLProtocol = configList.SSLProtocol
		}
		if config.CertType.empty() {
			config.CertType = configList.CertType
		}
		if config.ForceSet.empty() {
			config.ForceSet = configList.ForceSet
		}

		if config.SSLPubFilePath.empty() {
			config.SSLPubFilePath = "fullchain.pem"
		}
		if config.SSLPriFilePath.empty() {
			config.SSLPriFilePath = "privkey.pem"
		}
	}

	return configList
}

func checkFormatConfig(configList ConfigList) ConfigList {

	for i := 0; i < len(configList.List); i++ {
		config := &configList.List[i]
		var err error
		if config.DomainName == "" {
			log.Panic("DomainName not set")
		}
		if config.DomainName == "" {
			log.Panic("CertName not set")
		}
		if !config.SSLPubFilePath.exists() {
			log.Panic("CertFile Not Found!")
		}
		if !config.SSLPriFilePath.exists() {
			log.Panic("CertFile Not Found!")
		}
		var tempStr []byte
		tempStr, err = ioutil.ReadFile(string(config.SSLPubFilePath))
		if err != nil {
			log.Panic(err)
		}
		config.sSLPub = str(tempStr)
		tempStr, err = ioutil.ReadFile(string(config.SSLPriFilePath))
		if err != nil {
			log.Panic(err)
		}
		config.sSLPri = str(tempStr)
	}
	return configList
}
